package com.frame.database.operate;

import java.io.Serializable;
import java.sql.*;
import java.util.List;
import java.util.regex.Pattern;

import org.hibernate.*;

import com.frame.database.PageResult;
import com.frame.database.util.*;
import com.frame.util.*;

/**
 * hibernate操作基类
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2012
 * @Company:
 * @author:王海锋
 * @CreatedTime:2012-7-4 下午09:44:20
 * @version 1.0
 */
public class SessionOperate implements Operate{

	private Session session;
	public SessionOperate(){

	}
	public SessionOperate(Session session){
		this.session=session;
	}
	public void save(Object... tableBeans) throws HibernateException, Exception{
		session=getSession();
		for(Object tableBean:tableBeans)
			session.save(tableBean);
	}
	public void saveOrUpdate(Object tableBean) throws HibernateException, Exception{
		getSession().saveOrUpdate(tableBean);
	}
	public void delete(Object tableBean) throws HibernateException, Exception{
		getSession().delete(tableBean);
	}
	/**
	 * 删除
	 * @param tableName
	 * @param keyName
	 * @param keyValues
	 * @return
	 * @throws Exception
	 */
	public int delete(String tableName,String keyName,Object keyValues) throws Exception{
		Query query=getSession().createQuery("delete "+tableName +" where "+keyName+"=:"+keyName);
		query.setParameter(keyName, keyValues);
		int n=query.executeUpdate();
		return n;
	}
	public int delete(String sql,Object[] obj) throws Exception{
		Query query=getSession().createQuery(sql);
		if(obj!=null){
			for(int i=0;i<obj.length;i++)
				query.setParameter(i, obj[i]);
		}
		int n=query.executeUpdate();
		return n;
	}
	/**
	 * 批量删除
	 * @param tableClass
	 * @param keyName
	 * @param keyValues
	 * @throws HibernateException
	 * @throws Exception
	 */
	public int deleteBatch(String tableName,String keyName,Object[] keyValues) throws HibernateException, Exception{
		String sql="delete "+tableName+" where (";
		for(int i=0;i<keyValues.length;i++){
			if(i==0)
				sql+=keyName+"=?";
			else
				sql+=" or "+keyName+"=?";
		}
		sql+=")";
		Query query=getSession().createQuery(sql);
		for(int i=0;i<keyValues.length;i++)
			query.setParameter(i, keyValues[i]);
		int n=query.executeUpdate();
		return n;
	}
	/**
	 * 批量删除
	 * @param tableClass
	 * @param keyName
	 * @param keyValues
	 * @throws HibernateException
	 * @throws Exception
	 */
	public void deleteBatch(Class tableClass,String keyName,Object[] keyValues) throws HibernateException, Exception{
		Class c=Class.forName(tableClass.getName());
		session=getSession();
		if(keyValues!=null){
			for(int i=0;i<keyValues.length;i++){
				if(keyValues[i]!=null && !"".equals(keyValues[i])){
					Object obj=c.newInstance();
					BeanUtils.setValue(obj, keyName, keyValues[i]);
					session.delete(obj);
				}
			}

		}
	}
	/**
	 * JDBC批量删除（可用于因复合主键不能正常删除的情况）
	 * @param tableName
	 * @param keyName
	 * @param keyValues
	 * @return
	 * @throws Exception
	 */
	public void deletejdbc(String tableName,String[] keyName,Object[] keyValues) throws Exception{
		session=getSession();
		PreparedStatement ps=null;
		try{
			Connection con=session.connection();
			String sql="delete "+tableName+" where ";
			for(int i=0;i<keyName.length;i++){
				if(i==0)
					sql+=keyName[i]+"=?";
				else
					sql+=" and "+keyName[i]+"=?";
			}
			ps=con.prepareStatement(sql);
			for(int i=0;i<keyValues.length;i++){
				ps.setObject(i+1, keyValues[i]);
			}
			ps.executeUpdate();
		}catch(Exception e){
			throw new Exception("删除数据出错！",e);
		}
		finally{
			try{
				ps.close();
			}catch(Exception er){}
		}
	}

	public void update(Object tableBean) throws HibernateException, Exception{
		getSession().update(tableBean);
	}

	public int update(String sql,Object[] obj) throws Exception{
		session=getSession();
		Query query=session.createQuery(sql);
		if(obj!=null){
			for(int i=0;i<obj.length;i++)
				query.setParameter(i,obj[i]);
		}
		int n=query.executeUpdate();
		return n;
	}
	public int update(String sql,List parList) throws Exception{
		session=getSession();
		Query query=session.createQuery(sql);
		if(parList!=null){
			for(int i=0;i<parList.size();i++)
				query.setParameter(i,parList.get(i));
		}
		int n=query.executeUpdate();
		return n;
	}
	public Object getBean(Class tableBean,Serializable keyValue) throws HibernateException, Exception{
		return getSession().get(tableBean, keyValue);
	}

	public List query(String tableName,ConditionMap paramMap) throws HibernateException, Exception{
		String sql="select bean0 from "+tableName+" bean0";
		String whereSql="";
		String orderSql="";
		if(paramMap!=null){
			for(int i=0;i<paramMap.size();i++){
				if(whereSql.equals(""))
					whereSql+=" where "+paramMap.getCondition(i);
				else
					whereSql+=" and "+paramMap.getCondition(i);
			}
			List olist=paramMap.getOrder();
			if(olist!=null){
				for(int i=0;i<olist.size();i++){
					SelectItem item=(SelectItem)olist.get(i);
					if(orderSql.equals(""))
						orderSql+=" order by bean0."+item.getValue()+" "+item.getText();
					else
						orderSql+=",bean0."+item.getValue()+" "+item.getText();
				}
			}
		}

		sql+=whereSql+orderSql;
		Query query=getSession().createQuery(sql);
		if(paramMap!=null){
			for(int i=0;i<paramMap.paramSize();i++){
				query.setParameter(i,paramMap.getParamObj(i));
			}
		}
		return query.list();
	}

	public List queryBySql(String sql,Object[] obj) throws Exception{
		Query query=getSession().createQuery(sql);
		if(obj!=null){
			for(int i=0;i<obj.length;i++)
				query.setParameter(i,obj[i]);
		}
		return query.list();
	}

	public PageResult query(String tableName,ConditionMap paramMap,int size,int pageNo) throws Exception{
		int hipageno=0;
		if(pageNo<=0)
			pageNo=1;
		else
			hipageno=pageNo-1;
		String sql="select bean0 from "+tableName+" bean0";
		String whereSql="";
		String orderSql="";
		if(paramMap!=null){
			for(int i=0;i<paramMap.size();i++){
				if(whereSql.equals(""))
					whereSql+=" where "+paramMap.getCondition(i);
				else
					whereSql+=" and "+paramMap.getCondition(i);
			}
			List olist=paramMap.getOrder();
			if(olist!=null){
				for(int i=0;i<olist.size();i++){
					SelectItem item=(SelectItem)olist.get(i);
					if(orderSql.equals(""))
						orderSql+=" order by bean0."+item.getValue()+" "+item.getText();
					else
						orderSql+=",bean0."+item.getValue()+" "+item.getText();
				}
			}
		}
		sql+=whereSql+orderSql;
		session=getSession();
		Query query=session.createQuery(sql);
		Query query2 =session.createQuery("select count(bean0) from "+tableName+" bean0"+whereSql);
		query.setMaxResults(size);
		query.setFirstResult(hipageno*size);

		if(paramMap!=null){
			for(int i=0;i<paramMap.paramSize();i++){
				query.setParameter(i,paramMap.getParamObj(i));
				query2.setParameter(i,paramMap.getParamObj(i));
			}
		}

		List list=query.list();
		List list2=query2.list();
		PageResult ps=new PageResult(size,pageNo);
		ps.setList(list);
		int sum=new Integer(list2.get(0).toString()).intValue();
		ps.setResultCount(sum);
		return ps;
	}
	public PageResult queryBySql(String sql,Object[] obj,int size,int pageNo) throws Exception{
		int hipageno=0;
		if(pageNo<=0)
			pageNo=1;
		else
			hipageno=pageNo-1;
		session=getSession();
		Query query=session.createQuery(sql);
		query.setMaxResults(size);
		query.setFirstResult(hipageno*size);
		Pattern pattern=Pattern.compile("select(.+?)from", 2);
		String sql2=pattern.matcher(sql).replaceFirst("select count(*) from");
		if(sql2.indexOf("order by")!=-1){
			int n=sql2.lastIndexOf("order by");
			sql2=sql2.substring(0,n);
		}
		Query query2 =session.createQuery(sql2);
		if(obj!=null){
			for(int i=0;i<obj.length;i++){
				query.setParameter(i,obj[i]);
				query2.setParameter(i,obj[i]);
			}
		}
		PageResult ps=new PageResult(size,pageNo);
		ps.setList(query.list());
		List list2=query2.list();
		int sum=new Integer(list2.get(0).toString()).intValue();
		ps.setResultCount(sum);
		return ps;
	}
	public Session getSession() throws Exception {
		// TODO Auto-generated method stub
		return session;
	}
	public Session getSession(String ftg) throws Exception {
		// TODO Auto-generated method stub
		return session;
	}
}
